package userhandler

import (
	"github.com/gin-gonic/gin"
	"go-web-admin/app/user/model/dto"
	"go-web-admin/app/user/model/vo"
	"go-web-admin/app/user/service"
	"go-web-admin/response"
	"go-web-admin/utils"
)

type UserHandler struct {
	UserService *userservice.UserService
}

func NewUserHandler(userService *userservice.UserService) *UserHandler {
	return &UserHandler{
		UserService: userService,
	}
}

func (handler *UserHandler) FindById(c *gin.Context) {
	id := c.Param("id")

	userVo, err := handler.UserService.FindById(id)
	if err != nil {
		c.Error(err) // 会触发中间件中的 c.Errors
		return
	}

	response.OkWithData(c, userVo)
}

func (handler *UserHandler) Login(c *gin.Context) {

	var loginDto userdto.LoginDto
	if err := utils.BindJSON(c, &loginDto); err != nil {
		c.Error(err) // 会触发中间件中的 c.Errors
		return
	}

	accessToken, refreshToken, err := handler.UserService.Login(loginDto)
	if err != nil {
		c.Error(err)
		return
	}

	tokenVo := uservo.TokenVo{
		AccessToken:  accessToken,
		RefreshToken: refreshToken,
	}

	response.OkWithData(c, tokenVo)

}

func (handler *UserHandler) Register(c *gin.Context) {

	var regDto userdto.RegDto
	err := c.ShouldBindJSON(&regDto)
	if err != nil {
		c.Error(err) // 会触发中间件中的 c.Errors
		return
	}
	flag, err := handler.UserService.Register(&regDto)
	if err != nil {
		c.Error(err)
		return
	}

	if !flag {
		response.Fail(c, -1, "注册失败")
		return
	}

	response.Ok(c, "注册成功", "")
}
